package com.example.demo.use_demo.a_water_mark;

import cn.hutool.core.io.IoUtil;
import com.example.demo.exception.BusinessException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;

import java.awt.*;
import java.io.*;

public class PdfBoxWaterMarkUtil {

    public static InputStream addWaterRemark(InputStream inputStream, String fontFilePath, String waterMarkText) {
        PDDocument doc = null;
        try {
            // 读取原始 PDF 文件
            doc = PDDocument.load(inputStream);
            doc.setAllSecurityToBeRemoved(false);

            //必须是ttf字体
            PDFont font = PDType0Font.load(doc, new File(fontFilePath));

            float maxX;
            float maxY;
            float tempX;
            float tempY;
            float xStepLength = 100f;
            float yStepLength = 150f;
            float startX = 100f;
            float startY = 100f;
            PDPageContentStream contentStream;

            // 透明度
            PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
            r0.setNonStrokingAlphaConstant(0.2f);
            r0.setAlphaSourceFlag(false);
            for (PDPage page : doc.getPages()) {
                maxX = page.getBBox().getUpperRightX();
                maxY = page.getBBox().getUpperRightX();

                contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
                contentStream.setGraphicsStateParameters(r0);
                contentStream.setNonStrokingColor(new Color(200, 200, 200));
                contentStream.setFont(font, 20);

                contentStream.beginText();
                tempX = startX;
                while (tempX < maxX) {
                    tempY = startY;
                    while (tempY < maxY) {
                        contentStream.setTextMatrix(Matrix.getRotateInstance(45, tempX, tempY));
                        contentStream.showText(waterMarkText);
                        tempY += yStepLength;
                    }
                    tempX += xStepLength;
                }
                contentStream.endText();
                contentStream.close();
            }

            // 保存修改后的 PDF 文件
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            doc.save(outputStream);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            outputStream = null;
            inputStream = null;
            return byteArrayInputStream;
        } catch (Exception e) {
            throw new BusinessException("xxx");
        } finally {
            IoUtil.close(doc);
        }
    }

}
